const http = require("http");
const url = require("url");

const oUsers = []; // 全局临时存储

const server = http.createServer((req, resp) => {
  resp.setHeader("Content-Type", "application/json;charset=utf-8");
  // 1.请求方式是否是get
  if (req.method === "GET") {
    let urlObj = url.parse(req.url, true);
    // 登录
    if (urlObj.pathname === "/login") {
      let isLogin = oUsers.some(
        (item) =>
          item.username === urlObj.query.username && item.pwd === urlObj.query.pwd
      );
      resp.write(
        JSON.stringify({
          msg: isLogin ? "登录成功" : "登录失败",
          code: isLogin ? 1 : 0,
        })
      );
      resp.end();
    }
    // 注册
    if (urlObj.pathname === "/reg") {
      let isAdd = oUsers.some((item) => item.username === urlObj.query.username);
      if (isAdd) {
        resp.write(JSON.stringify({ msg: "该用户已注册!", code: 0 }));
      } else {
        oUsers.push(urlObj.query);
        resp.write(JSON.stringify({ msg: "注册成功!", code: 1 }));
      }
      resp.end();
    }
  } else {
    resp.write("目前只支持get请求");
    resp.end();
  }
});

server.listen(8080, () => {
  console.log("服务器启动完毕!");
});